﻿using System;
using System.Collections;
using NLite.Collections;
using NLite.Internal;
using NLite.Threading.Internal;

namespace NLite.Threading
{
    /// <summary>
    /// 
    /// </summary>
    public static class Local
    {
        
        internal static readonly IDataContext _dataContext = new LocalDataContext();

       


        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static object Get(object key)
        {
            return _dataContext.Data[key];
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void Set(object key, object value)
        {
            _dataContext.Data[key] = value;
        }
       
    }

    namespace Internal
    {
        class LocalDataContext : IDataContext
        {
            [ThreadStatic]
            private static HashtableDataCollection _localData;
            private static readonly object LocalDataHashtableKey = new object();

            public IDataCollection Data
            {
                get
                {
                    if (!NLiteEnvironment.IsWeb)
                    {
                        if (_localData == null)
                            _localData = new HashtableDataCollection();
                        return _localData;
                    }
                    else
                    {
                        var web_hashtable = HttpContextWrapper.Items[LocalDataHashtableKey] as HashtableDataCollection;
                        if (web_hashtable == null)
                        {
                            web_hashtable = new HashtableDataCollection();
                            HttpContextWrapper.Items[LocalDataHashtableKey] = web_hashtable;
                        }
                        return web_hashtable;
                    }
                }
            }
        }
        class LocalState : Hashtable, ICache, IApplication, ISession { }
    }
}
